nestjs-command, a nest command line tool
If you want to integrate the 2dsphere
index creation into your NestJS CLI workflow, the best approach is to create a custom NestJS command that can be executed using nest
commands. This will follow the NestJS CLI style and allow better integration into your application lifecycle.
1. Create a Custom NestJS Command
NestJS allows creating command-line tools using nestjs-command
or nestjs-console
. We will use nestjs-command
for this.
Install Required Dependencies
Run:
pnpm add nestjs-command
2. Implement the Command in src/commands/create-index.command.ts
Create a new directory src/commands/
and add a file create-index.command.ts
:
import { Injectable } from '@nestjs/common';
import { Command } from 'nestjs-command';
import { MongoClient } from 'mongodb';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class CreateIndexCommand {
constructor(private readonly configService: ConfigService) {}
@Command({
command: 'db:create-index',
describe: 'Create 2dsphere index on address.location.coordinates',
})
async createIndex() {
const uri = this.configService.get<string>('DATABASE_URL');
if (!uri) {
console.error('❌ DATABASE_URL is not set.');
return;
}
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db(); // Get the default database from the connection string
await db.collection('AcademyModel').createIndex({ 'address.location.coordinates': '2dsphere' });
console.log('✅ 2dsphere index created on address.location.coordinates');
} catch (error) {
console.error('❌ Error creating 2dsphere index:', error);
} finally {
await client.close();
}
}
}
3. Register the Command in app.module.ts
Modify app.module.ts
to include the command:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CommandModule } from 'nestjs-command';
import { CreateIndexCommand } from './commands/create-index.command';
@Module({
imports: [
ConfigModule.forRoot(), // Load environment variables
CommandModule,
],
providers: [CreateIndexCommand],
})
export class AppModule {}
4. Run the Command
Now you can run the custom command using the NestJS CLI:
pnpm run start db:create-index
5. Automate It in package.json
Modify your package.json
script to run the Prisma migration and then create the index:
"scripts": {
"prisma:push": "npx prisma db push && pnpm run start db:create-index"
}
Now, whenever you run:
pnpm run prisma:push
It will:
- Push the Prisma schema to MongoDB.
- Automatically create the
2dsphere
index via the custom NestJS command.
Final Thoughts
✅ Follows NestJS CLI conventions
✅ Better error handling than raw shell scripts
✅ Uses NestJS dependency injection (ConfigService for env variables)
✅ Easier to extend for future commands
Would you like to add logging or extend this command further? 🚀